// Copyright(c) 2008 Tri Tech Information Systems Inc. 
// Distributed under the Boost Software License, Version 1.0.
//     (See accompanying file ../../LICENSE_1_0.txt or copy at
//           http://www.boost.org/LICENSE_1_0.txt)
//     
#include <qt.h>
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>

template<typename T>
void release_qt_pointer(IWrapper * wrap)
{
    T & ptr = boost::python::extract< T& >(wrap->self());
    ptr.release();
}

template<typename T>
class QtPointer
{
    public:
        boost::shared_ptr< QGuardedPtrPrivate > m_ptr;

        typedef T element_type;

        QtPointer(T * ptr = 0):
            m_ptr(new QGuardedPtrPrivate(ptr) )
        {
            using namespace boost::python;

            if( IWrapper * wrapper = dynamic_cast<IWrapper*>(ptr) )
            {
                if(ptr->parent() && !wrapper->owned())
                    wrapper->take_ownership( &release_qt_pointer< QtPointer<T> >);
            }

       }

        template<typename OtherPtr>
        QtPointer( QtPointer<OtherPtr> ptr) :
            m_ptr( ptr.m_ptr )
        {
        }            

        ~QtPointer()
        {
            // Python no longer has any references to this object
            // Does Qt?
            if( m_ptr.unique() && get() && !get()->parent() )
            {
                // This object is an orphan
                // It should be destroyed
                delete get();
            }
        }    

        T * get() const
        {
            return reinterpret_cast<T*>(m_ptr.get()->object());
        }

        T & operator * () const
        {
            return *get();        
        }

        void release()
        {
            m_ptr.reset(new QGuardedPtrPrivate(0));
        }

};

template<typename T>
T * get_pointer( const QtPointer<T> & ptr)
{
    return ptr.get();
}




